#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import win32com.client as wc
import os
from docx import Document
import re
import eel
from utils.anki_manage import AnkiManage

# 切分题用的正则
re_topic_str =  r'(\d+)\.([\s\S]+?)A\)([\s\S]+?)B\)([\s\S]+?)C\)([\s\S]+?)D\)([\s\S]+?)\n'
re_extra_str = r'【([\u4e00-\u9fa5]+)】(.*)'
re_topic = re.compile(re_topic_str)
re_extra = re.compile(re_extra_str)
fileName = r"C:\Users\19135\Desktop\继教与网络学院学位考试模拟试题二及答案.doc"


fieldMap={
    "定位句":'f_positioning_sentense',
    "答案句":'f_answer_sentence',
    "答案":'f_rightanswer',
    "解析":'f_answeranalyce'
}


# 全部的题
allText =''

def start(fileName):
    # 非docx就转为docx
    fileName = doSaveAas(fileName)
    # 读取文档
    document = Document(fileName)
    # 第一级单位是段落
    paragraphs = document.paragraphs

    totalText=  ''
    # 输出每一段的内容
    for para in paragraphs:
        totalText += para.text +'\n'
    return totalText



def analyzeSingle(topic_text):
    global fileName
    topic_res = re_topic.search(topic_text)
    if(topic_res==None):
        return None
    choiceNote = {
        'f_comefrom': '',
        'f_positioning_sentense': '',
        'f_answer_sentence': '',
        'f_question': '',
        'f_qustionindex': '',
        'f_rightanswer': '',
        'f_answeroptions': '',
        'f_answeranalyce': ''
    }
    choiceNote['f_comefrom'] = os.path.split(fileName)[1]

    # topic's index between answer and option
    startIndex, endIndex = topic_res.span()
    # topic's total string.
    # inject answer and options
    choiceNote['f_qustionindex'] = stripLine(topic_res.groups()[0])
    choiceNote['f_question'] = topic_res.groups()[1].strip()
    choiceNote['f_comefrom'] = choiceNote['f_comefrom'] + "\t" + choiceNote['f_qustionindex']

    answer = ''
    for item in topic_res.groups()[2:]:
        answer += stripLine(item) + '\n'
    # cut last \n
    answer = answer[:len(answer)-1]
    choiceNote['f_answeroptions'] = answer
    # cut totalText's known content
    topic_text = topic_text[endIndex:]

    # try to find text in 【】
    while (True):
        # get next line text
        line_feed_index = topic_text.find('\n')
        if (line_feed_index == -1):
            break
        line_text = topic_text[:line_feed_index]
        # search whether 【】feild
        extra_res = re_extra.search(line_text)
        if (extra_res == None):
            break;
        key = extra_res.groups()[0]
        value = extra_res.groups()[1]
        choiceNote[fieldMap[stripLine(key)]] = stripLine(value)

        # trun topic_text to text of next line
        topic_text = topic_text[line_feed_index + 1:]

    # residue content and choice Note
    return (choiceNote,topic_text)

# 将无法读取的非docx格式转换为 docx
def doSaveAas(fileName):
    if(os.path.splitext(fileName)[1]=='docx'):
        return fileName
    # 尝试各种厂家格式
    try:
        word = wc.Dispatch("kwps.Application")
    except:
        try:
            word = wc.Dispatch("wps.Application")
        except:
            word = wc.Dispatch("Word.Application")


    doc = word.Documents.Open(fileName)  # 目标路径下的文件
    # 另存为一份同名的docx
    newFileName = os.path.splitext(fileName)[0] + '.docx'
    doc.SaveAs(newFileName, 12, False, "", True, "", False, False, False, False)  # 转化后路径下的文件
    doc.Close()
    word.Quit()
    return newFileName

def stripLine(text):
    if(isinstance(text,int)):
        return text;
    if(not isinstance(text,str)):
        raise Exception('该类型无法去空格')
    text =  text.strip()
    text = text.replace('\n','')
    text = text.replace('\t','')
    return text

# inject javascript
@eel.expose
def nextTopic():
    global allText
    res = analyzeSingle(allText)
    if(res == None):
        return None
    note = res[0]
    allText = res[1]
    return note

@eel.expose
def addNote(deckName,modelName,data):
    return AnkiManage.addNote(deckName,modelName,data)

if __name__ == '__main__':
    # createUI
    allText =  start(fileName)
    eel.init('web')
    eel.setDeckNames(AnkiManage.deckNames())
    eel.setModelNames(AnkiManage.modelNames())
    # eel.start('main.html', port=0,size=(500, 800))
    # 使用固定的端口，保证前台可以取到sessionStorage缓存
    eel.start('main.html', size=(500, 800))
